package com.mylife.user.service.impl;

import com.mylife.pojo.Result;
import com.mylife.service.ReturnCodes;
import com.mylife.service.ReturnMessage;
import com.mylife.service.HttpStatus;
import com.mylife.user.mapper.UserMapper;
import com.mylife.user.service.UserService;
import com.mylife.user.vo.params.UserAccountParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户信息serviceImpl
 * @author blueCat
 * @since 2022-01-08
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户账号注册
     *
     * @param params
     * @return boolean
     */
    @Override
    public Result registerAccount(UserAccountParams params) {
        //查询用户名是否存在，若存在返回false
        int i = userMapper.queryUserByName(params.getUsername());
        if (i > 0){
            return Result.setFail(ReturnCodes.USER_EXIT_ALREADY, ReturnMessage.USER_EXIT_ALREADY);
        }
        //用户名不存在执行插入
        //插入前处理前端传来的时间格式
        if (params.getBirthday() != null && params.getBirthday() != ""){
            params.setBirthday(params.getBirthday().substring(0,10));
        }
        userMapper.registerUserAccount(params);
        return Result.setSuccess(HttpStatus.SUCCESS,"恭喜注册成功！");
    }

    /**
     * 用户登录
     *
     * @param params
     * @return boolean
     */
    @Override
    public Result loginAccount(UserAccountParams params, HttpServletResponse response) {
        //查询用户名是否存在
        int i = userMapper.queryUserByName(params.getUsername());
        if (i == 0){
            return Result.setFail(ReturnCodes.USER_NOT_EXIT,ReturnMessage.USER_NOT_EXIT);
        }
        //检查账号密码
        i = userMapper.checkAccount(params.getUsername(),params.getPassword());
        if (i == 0){
            return Result.setFail(ReturnCodes.PASSWORD_WRONG,ReturnMessage.PASSWORD_WRONG);
        }
        //查询真实姓名
        String realName = userMapper.queryRealName(params.getUsername());
        if (realName == null){
            realName = "没有透露姓名的你";
        }
        //将真实姓名和用户名存储在cookie中
        Cookie[] cookies = new Cookie[2];
        cookies[0] = new Cookie("realName",realName);
        cookies[1] = new Cookie("username",params.getUsername());
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return Result.setSuccess(HttpStatus.SUCCESS,"登陆成功！");
    }
}
